package com.dao;

import com.entity.User;
import com.util.DBconnection;
import org.junit.Test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{


    @Override
    public boolean register(User user) {
        boolean flag = false;
        DBconnection.init();
        int i = DBconnection.addUpdDel("insert into users_table(name,number,address) " +
                "values('"+user.getName()+"','"+user.getNumber()+"','"+user.getAddress()+"')");
        if(i>0){
            flag = true;
        }
        DBconnection.closeConn();
        return flag;
    }

    @Override
    public List<User> getUserAll() {
        List<User> list = new ArrayList<User>();
        try {
            DBconnection.init();
            ResultSet rs = DBconnection.selectSql("select * from users_table");
            while(rs.next()){
                User user = new User();

                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setNumber(rs.getString("number"));
                user.setAddress(rs.getString("address"));

                list.add(user);
            }
            DBconnection.closeConn();
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean delete(int id) {
        boolean flag = false;
        DBconnection.init();
        String sql = "delete  from users_table where id="+id;
        int i = DBconnection.addUpdDel(sql);
        if(i>0){
            flag = true;
        }
        DBconnection.closeConn();
        return flag;
    }

    @Override
    public boolean update(int id, String name, String number, String address) {
        boolean flag = false;
        DBconnection.init();
        String sql ="update users_table set name ='"+name
                +"' , number ='"+number
                +"' , address ='"+address
                +"' where id = "+id;
        int i = DBconnection.addUpdDel(sql);
        if(i>0){
            flag = true;
        }
        DBconnection.closeConn();
        return flag;

    }

    @Test
    public void test1() {
        List<User> ans = getUserAll();

        for (User t : ans) System.out.println(t);

    }

}
